package com.molyfun.parents.activity.classroom;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.common.listactivity.ListActivity;
import com.molyfun.parents.dao.entity.SingleChatDB;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.dao.gen.SingleChatDBDao;
import com.molyfun.parents.rest.bean.AnnouncementListResponse;
import com.molyfun.parents.rest.bean.CreateSingleConversionRequest;
import com.molyfun.parents.rest.bean.StringResponse;
import com.molyfun.parents.rest.bean.TeamUserlistResponse;
import com.molyfun.parents.utils.AndroidBug5497Workaround;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.StrokeTextView;
import com.squareup.picasso.Picasso;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.molyfun.parents.activity.classroom.ClassRoomActivity.FLAG_CLASS_IS_EXPIRE;
import static com.molyfun.parents.activity.classroom.ClassRoomActivity.FLAG_CLASS_TEAM_BEAN_ID;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:09/10/2017.
 */

public class ClassRoomSettingActivity extends BaseActivity implements View.OnClickListener {
    protected static final String TAG = "EaseChatFragment";
    /**
     * params to fragment
     */
    @InjectView(R.id.title)
    StrokeTextView mTitle;
    @InjectView(R.id.base_title_left)
    ImageView mBackBtn;
    @InjectView(R.id.user_layout)
    LinearLayout mUserLayout;
    @InjectView(R.id.view_all_users)
    StrokeTextView mViewUserTv;
    @InjectView(R.id.view_announcement_layout)
    LinearLayout mAnnouncementLayout;
    @InjectView(R.id.announcement_view)
    AnnouncementView mAnnouncementView;

    private String mTeamBeanId;

    private ArrayList<TeamUser> mUserList;

    private boolean isExpire;//课程是否过期

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_classroom_setting);
        AndroidBug5497Workaround.assistActivity(this);
        getSupportActionBar().setTitle("");
        super.onCreate(savedInstanceState);
        ButterKnife.inject(this);
        mBackBtn.setOnClickListener(this);
        mTitle.setText("群成员");
        mAnnouncementLayout.setOnClickListener(this);

        mTeamBeanId = getIntent().getStringExtra(FLAG_CLASS_TEAM_BEAN_ID);
        isExpire = getIntent().getBooleanExtra(FLAG_CLASS_IS_EXPIRE, false);
        getTeamMemberList();
        getTeamNoticeList();

        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;

        mViewUserTv.setOnClickListener(this);

    }

    public static final void startActivity(Context context, String teamBeanId, boolean isExpire) {
        Intent intent = new Intent();
        intent.setClass(context, ClassRoomSettingActivity.class);
        intent.putExtra(FLAG_CLASS_TEAM_BEAN_ID, teamBeanId);
        intent.putExtra(FLAG_CLASS_IS_EXPIRE, isExpire);
        context.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.view_announcement_layout:
                ListActivity.startAnnouncementActivity(this, mTeamBeanId);
                break;
            case R.id.view_all_users:
                ClassRoomAllUsersActivity.startActivity(ClassRoomSettingActivity.this, mUserList, isExpire);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void getTeamMemberList() {
        Call<TeamUserlistResponse> call = MFPApplication.getInstance().getRestClient().getTeamMemberList(mTeamBeanId, 1);
        call.enqueue(new Callback<TeamUserlistResponse>() {
            @Override
            public void onResponse(Call<TeamUserlistResponse> call, Response<TeamUserlistResponse> response) {
                if (response.body() != null) {
                    mUserLayout.removeAllViews();
                    mUserList = new ArrayList<>(response.body().getData());
                    if (mUserList != null && mUserList.size() > 0) {

                        int recycleCount = mUserList.size() / 3;
                        if ((mUserList.size() % 3) > 0) {
                            recycleCount += 1;
                        }
                        if (recycleCount > 5) {
                            recycleCount = 5;
                            mViewUserTv.setVisibility(View.VISIBLE);
                        }
                        for (int position = 0; position < recycleCount; position++) {
                            View view = LayoutInflater.from(ClassRoomSettingActivity.this).inflate(R.layout.layout_class_three_user_horizonal_cell, null, false);
                            CircleImageView imageView1 = (CircleImageView) view.findViewById(R.id.avator1);
                            CircleImageView imageView2 = (CircleImageView) view.findViewById(R.id.avator2);
                            CircleImageView imageView3 = (CircleImageView) view.findViewById(R.id.avator3);

                            ImageView admin1 = (ImageView) view.findViewById(R.id.admin1);
                            ImageView admin2 = (ImageView) view.findViewById(R.id.admin2);
                            ImageView admin3 = (ImageView) view.findViewById(R.id.admin3);

                            TextView userName1 = (TextView) view.findViewById(R.id.user_name1);
                            TextView studentName1 = (TextView) view.findViewById(R.id.student_name1);
                            TextView userName2 = (TextView) view.findViewById(R.id.user_name2);
                            TextView studentName2 = (TextView) view.findViewById(R.id.student_name2);
                            TextView userName3 = (TextView) view.findViewById(R.id.user_name3);
                            TextView studentName3 = (TextView) view.findViewById(R.id.student_name3);

                            final TeamUser teamUser1 = mUserList.get(position * 3);
                            if (!TextUtils.isEmpty(teamUser1.getHeadimgurl())) {
                                Picasso.with(ClassRoomSettingActivity.this)
                                        .load(teamUser1.getHeadimgurl())
                                        .placeholder(R.mipmap.ic_header_default)
                                        .into(imageView1);
                            } else {
                                imageView1.setImageResource(R.mipmap.ic_header_default);
                            }
                            userName1.setText(teamUser1.getUsername());
                            if(!TextUtils.isEmpty(teamUser1.getUsertype()) && teamUser1.getUsertype().equals("1")){
                                admin1.setVisibility(View.GONE);
                                studentName1.setVisibility(View.VISIBLE);
                                studentName1.setText(teamUser1.getStudentname());
                            }else{
                                admin1.setVisibility(View.VISIBLE);
                                studentName1.setVisibility(View.GONE);
                            }
                            imageView1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startSingleConversion(teamUser1.getUsertype(), teamUser1.getUserid(), teamUser1.getUsername(), teamUser1.getHeadimgurl());
                                }
                            });

                            if (position * 3 + 1 < mUserList.size()) {
                                final TeamUser teamUser2 = mUserList.get(position * 3 + 1);
                                if (!TextUtils.isEmpty(teamUser2.getHeadimgurl())) {
                                    Picasso.with(ClassRoomSettingActivity.this)
                                            .load(teamUser2.getHeadimgurl())
                                            .placeholder(R.mipmap.ic_header_default)
                                            .into(imageView2);
                                } else {
                                    imageView2.setImageResource(R.mipmap.ic_header_default);
                                }
                                userName2.setText(teamUser2.getUsername());
                                if(!TextUtils.isEmpty(teamUser2.getUsertype()) && teamUser2.getUsertype().equals("1")){
                                    studentName2.setVisibility(View.VISIBLE);
                                    studentName2.setText(teamUser2.getStudentname());
                                    admin2.setVisibility(View.GONE);
                                }else{
                                    studentName2.setVisibility(View.GONE);
                                    admin2.setVisibility(View.VISIBLE);
                                }
                                imageView2.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startSingleConversion(teamUser2.getUsertype(), teamUser2.getUserid(), teamUser2.getUsername(), teamUser2.getHeadimgurl());
                                    }
                                });
                            }


                            if (position * 3 + 2 < mUserList.size()) {
                                final TeamUser teamUser3 = mUserList.get(position * 3 + 2);
                                if (!TextUtils.isEmpty(teamUser3.getHeadimgurl())) {
                                    Picasso.with(ClassRoomSettingActivity.this)
                                            .load(teamUser3.getHeadimgurl())
                                            .placeholder(R.mipmap.ic_header_default)
                                            .into(imageView3);
                                } else {
                                    imageView3.setImageResource(R.mipmap.ic_header_default);
                                }
                                userName3.setText(teamUser3.getUsername());
                                if(!TextUtils.isEmpty(teamUser3.getUsertype()) && teamUser3.getUsertype().equals("1")){
                                    studentName3.setVisibility(View.VISIBLE);
                                    studentName3.setText(teamUser3.getStudentname());
                                    admin3.setVisibility(View.GONE);
                                }else{
                                    studentName3.setVisibility(View.GONE);
                                    admin3.setVisibility(View.VISIBLE);
                                }
                                imageView3.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startSingleConversion(teamUser3.getUsertype(), teamUser3.getUserid(), teamUser3.getUsername(), teamUser3.getHeadimgurl());
                                    }
                                });
                            }
                            mUserLayout.addView(view);
                        }

                    }

                }
            }

            @Override
            public void onFailure(Call<TeamUserlistResponse> call, Throwable t) {

            }
        });
    }

    private void startSingleConversion(final String type, final String userId, final String userName, final String cover) {
        if(isExpire){
            toast("课程已经过期，不能聊天");
            return;
        }
        if(!TextUtils.isEmpty(userId) && userId.equals(MFPApplication.getInstance().getUser().getId())){
            toast("不能和自己聊天");
            return;
        }

        showProgressDialog();
        CreateSingleConversionRequest createSingleConversionRequest = new CreateSingleConversionRequest();
        createSingleConversionRequest.setTarget(userId);
        createSingleConversionRequest.setTargettype(type);
        Call<StringResponse> call = MFPApplication.getInstance().getRestClient().createSingleConversation(createSingleConversionRequest);
        call.enqueue(new Callback<StringResponse>() {
            @Override
            public void onResponse(Call<StringResponse> call, Response<StringResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (!TextUtils.isEmpty(response.body().getData())) {
                        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
                        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
                        DaoSession daoSession = daoMaster.newSession();
                        SingleChatDBDao mSingleChatDBDao = daoSession.getSingleChatDBDao();
                        SingleChatDB singleChatDB = mSingleChatDBDao.queryBuilder().where(SingleChatDBDao.Properties.Conversationid.eq(response.body().getData())).build().unique();
                        if (singleChatDB != null) {
                            int unreadCount = singleChatDB.getUnReadMsgCount();
                            singleChatDB.setUnReadMsgCount(unreadCount + 1);
                            singleChatDB.setLastMsgTime(System.currentTimeMillis());
                        } else {
                            singleChatDB = new SingleChatDB();
                            singleChatDB.setConversationid(response.body().getData());
                            singleChatDB.setTxuserid(PreferencesStorageUtil.getIMUserName(ClassRoomSettingActivity.this));
                            singleChatDB.setCover(cover);
                            singleChatDB.setLastMsgTime(System.currentTimeMillis());
                            singleChatDB.setUnReadMsgCount(1);
                            singleChatDB.setTxuserid(PreferencesStorageUtil.getIMUserName(ClassRoomSettingActivity.this));

                            singleChatDB.setName(userName);
                            singleChatDB.setIsTeam(false);
                            singleChatDB.setUserId(userId);
                            singleChatDB.setTargettype(type);
                        }
                        mSingleChatDBDao.insertOrReplace(singleChatDB);

                        SingleChatActivity.startActivity(ClassRoomSettingActivity.this, response.body().getData(), userId, userName, type);
                    }
                }
            }

            @Override
            public void onFailure(Call<StringResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    private void getTeamNoticeList() {
        Call<AnnouncementListResponse> call = MFPApplication.getInstance().getRestClient().getTeamNoticeList(mTeamBeanId, 1);
        call.enqueue(new Callback<AnnouncementListResponse>() {
            @Override
            public void onResponse(Call<AnnouncementListResponse> call, Response<AnnouncementListResponse> response) {
                if (response.body() != null) {
                    if (response.body().getData() != null && response.body().getData().size() > 0) {
                        AnnouncementListResponse.AnnouncementBean announcementBean = response.body().getData().get(0);
                        mAnnouncementLayout.setVisibility(View.VISIBLE);
                        mAnnouncementView.setVisibility(View.VISIBLE);
                        mAnnouncementView.initData(announcementBean, true);
                    }
                }
            }

            @Override
            public void onFailure(Call<AnnouncementListResponse> call, Throwable t) {

            }
        });
    }

}
